// pages/onlineAnswer/OnlineAnswer.js
const app = getApp();
var WebIM = require('../../utils/WebIM.js');
var WebIM = WebIM.default

Page({
  /**
   * 页面的初始数据
   */
  data: {
    url: '',
    initialState: false, // 页面元素初始显示状态
    problemArray: [],
    key: null, //后台缓存标识
    testState: true, //题目初始状态
    onlineState: false, //在线答题返回
    hxStatus: false, //环信状态
  },

  /**
   * 警告框
   */
  caveat: function() {
    wx.showModal({
      title: '提示',
      content: '答案未识别完,请稍等~',
      showCancel: false,
      success(res) {
        if (res.confirm) {
          return;
        }
      }
    })
  },

  /**
   * 获取答题卡信息
   */
  getAnswerInfo: function() {
    var _this = this,
      user_id = wx.getStorageSync('userId'),
      _task_id = _this.data.task_id,
      _paper_ids = _this.data.paper_ids;
    wx.showLoading({
      title: '加载中',
      //mask: true
    })
    var problemArray = wx.getStorageSync(user_id + '-' + _task_id + '-' + _paper_ids);
    if (!problemArray || problemArray[0].paper_answer_status == 1) {
      wx.request({
        url: app.globalData.URL + '/kmapping/WebAppAjax/getTopicStatusBySplitAndTask?' + app.globalData.URLBOOL,
        method: 'GET',
        data: {
          task_id: _task_id,
          paper_ids: _paper_ids
        },
        success(res) {
          if (res.data.error_code == 0) {
            var _problemArray = res.data.data;
            _this.setData({
              problemArray: _problemArray,
            })
            if (_problemArray[0].paper_answer_status == 0) {
              // 2019-8-6 在服务器端做缓存
              // wx.setStorageSync(user_id + '-' + _task_id + '-' + _paper_ids, _problemArray)
              _this.testAnalysis();
            }
          } else if (res.data.error_code == 10002) {
            _this.setData({
              problemArray: []
            })
          }
          _this.fromCache();
        }
      })
    } else {
      wx.request({
        url: app.globalData.URL + '/kmapping/WebAppAjax/getTopicStatusBySplitAndTask?' + app.globalData.URLBOOL,
        method: 'GET',
        data: {
          task_id: _task_id,
          paper_ids: _paper_ids
        },
        success(res) {
          if (res.data.error_code == 0) {
            var _problemArray = res.data.data;
            var topics = _problemArray[0].topics
            for (let i = 0; i < topics.length; i++) {
              problemArray[0].topics[i].user_answer_paper_status = topics[i].user_answer_paper_status;
              problemArray[0].topics[i].is_add_wrong = topics[i].is_add_wrong;
            }
            _this.setData({
              problemArray: problemArray,
            })
            // wx.setStorageSync(user_id + '-' + _task_id + '-' + _paper_ids, problemArray)
            _this.testAnalysis();
            _this.setData({
              initialState: true
            })
          }
          _this.fromCache();
        }
      })
    }
  },

  /**
   * 在线答题入口
   */
  onlineAnswer: function() {
    var _this = this,
      key = _this.data.key,
      hxStatus = _this.data.hxStatus;
    if (hxStatus) {
      _this.caveat();
      return;
    }
    wx.navigateTo({
      url: '/pages/zyWebView/zyWebView?url='+ _this.data.url +'/kmapping/Webapp/kmappingPaperDetail&key=' + key + '&subscript=0&index=0&online=1',
    })
  },

  /**
   * 题目数据分析
   */
  testAnalysis: function() {
    var _this = this,
      _problemArray = _this.data.problemArray;
    if (_problemArray[0].paper_answer_status == 0) {
      var topics = _problemArray[0].topics;
      for (var i = 0; i < topics.length; i++) {
        if (topics[i].user_answer_paper_status == 1) {
          _this.hxDealWith();
        }
        if (topics[i].answer_flag == 1) {
          _this.setData({
            testState: false
          })
        }
      }
      _this.getaddTaskLog(2) //学习上报
    }
  },

  /**
   * 获取下一题信息
   */
  getRsourceDetailInfo() {
    var that = this;
    wx.showLoading({
      title: '加载中',
      //mask: true
    })
    wx.request({
      url: app.globalData.URL + '/kmapping/WebAppAjax/getRsourceDetailInfo?' + app.globalData.URLBOOL,
      dataType: 'json',
      method: 'GET',
      data: {
        resource_id: that.data.resource_id,
        type: that.data.type,
        task_id: that.data.task_id,
        structure_id: that.data.structure_id,
        kmapping_id: that.data.kmapping_id
      },
      success: function(res) {
        var _res = res.data;
        wx.hideLoading();
        if (_res.error_code == 0) {
          that.setData({
            'next': _res.data.next,
            'previous': _res.data.previous,
            'resource_info': _res.data.resource_info,
            'paper_ids': _res.data.resource_info.paper_info.id
          })
          that.getAnswerInfo();
        }
      }
    })
  },

  /**
   * 将题目信息录入缓存
   */
  fromCache: function(call) {
    var _this = this;
    wx.request({
      url: app.globalData.URL + '/kmapping/WeixinAppAjax/addTopicAnswerToCache?' + app.globalData.URLBOOL,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        topic_info: JSON.stringify(_this.data.problemArray)
      },
      success: function(res) {
        var _res = res.data;
        if (_res.error_code == 0) {
          wx.hideLoading();
          var key = _res.data.key;
          console.log(key);
          _this.setData({
            key: key,
            initialState: true
          })
        }
      }

    })
  },

  /**
   * ai拍题入口
   */
  aiQuestion: function() {
    var _this = this,
      paper_id = _this.data.resource_info.paper_info.id,
      task_id = _this.data.task_id,
      hxStatus = _this.data.hxStatus;
    if (hxStatus) {
      _this.caveat();
      return;
    }
    wx.navigateTo({
      url: '/pages/testImg/testImg?paper_id=' + paper_id + '&paper_download_task_id=' + task_id + '&online=' + 1
    })

  },

  /**
   * 判断是否有效试题
   */
  judgeEffective: function(dtId, arr) {
    var _this = this,
      user_id = wx.getStorageSync('userId'),
      paper_id = _this.data.resource_info.paper_info.id,
      task_id = _this.data.task_id,
      download_task_id = dtId,
      paper_download_task_id = arr[1];
    wx.showLoading({
      title: '加载中...',
      //mask: true
    })
    wx.request({
      url: app.globalData.URL + '/kmapping/WebAppAjax/checkPageStatus?' + app.globalData.URLBOOL,
      method: 'GET',
      data: {
        user_id: user_id,
        paper_id: paper_id,
        task_id: task_id,
        download_task_id: download_task_id,
        paper_download_task_id: paper_download_task_id
      },
      success: function(res) {
        console.log(res);
        var _res = res.data;
        wx.hideLoading();
        if (_res.error_code == 0) {
          if (arr[0] == 1101) {
            wx.navigateTo({
              url: '/pages/testImg/testImg?paper_id=' + paper_id + '&app_id=' + arr[0] + '&paper_download_task_id=' + arr[1] + '&page=' + arr[2] + '&download_task_id=' + arr[3] + '&online=' + 1
            })
            _this.setData({
              download_task_id: arr[3],
              paper_download_task_id: arr[1]
            })
          } else if (arr[3] == 1101) {
            wx.navigateTo({
              url: '/pages/testImg/testImg?app_id=' + arr[3] + '&paper_download_task_id=' + arr[1] + '&page=' + arr[2] + '&download_task_id=' + arr[0] + '&online=' + 1
            })
            _this.setData({
              download_task_id: arr[0],
              paper_download_task_id: arr[1]
            })
          }
        } else {
          wx.showToast({
            title: _res.error_msg,
            icon: 'none',
            mask: true,
            duration: 2000
          })
        }
      }
    })
  },

  /**
   * 开启环信消息接收
   */
  hxDealWith: function() {
    var _this = this;
    WebIM.conn.listen({
      onTextMessage: function(message) {
        if (message) {
          var ext = JSON.parse(message.ext.ext);
          console.log(ext)
          if (ext.msg_type == 28) {
            var messageData = JSON.parse(ext.msg_content);
            var task_id = messageData.task_id,
              paper_id = messageData.resource_id,
              key = messageData.key;
            app.dealMessage(key, task_id, paper_id);
            _this.getAnswerInfo();
            _this.setData({
              hxStatus: false
            })
          }
        }
      },
    })
  },

  /**
   * 下一任务跳转
   */
  nextTaskHandle: function(e) {
    var that = this,
      next_url = that.data.next.weixinapp_url;
    wx.redirectTo({
      url: next_url,
    })
  },

  /**
   * 提交答案
   */
  submitAnswer: function() {
    var _this = this,
      problemArray = _this.data.problemArray,
      user_id = wx.getStorageSync('userId'),
      task_id = _this.data.task_id,
      paper_ids = _this.data.paper_ids,
      kmapping_id = _this.data.kmapping_id;
    var _answer = {
      paper_id: problemArray[0].id,
      answer: []
    };
    var topics = problemArray[0].topics;
    for (var k = 0; k < topics.length; k++) {
      var myAnswer = {
        "resource_type": 0,
        "answer": "",
        "topic_id": null
      };
      if (typeof topics[k].paper_answer.answer != 'undefined') {
        if (typeof topics[k].paper_answer.answer.resource != 'undefined') {
          if (typeof topics[k].paper_answer.answer.resource.format_image != 'undefined') {
            var format_image = [];
            for (let x = 0; x < topics[k].paper_answer.answer.resource.format_image.length; x++) {
              format_image.push(topics[k].paper_answer.answer.resource.format_image[x].md);
            }
            myAnswer.resource_mds = format_image.join();
            if (format_image.length) {
              myAnswer.resource_type = 1;
            }
          }
        }
        if (typeof topics[k].paper_answer.answer.stu_answer != 'undefined') {
          myAnswer.answer = topics[k].paper_answer.answer.stu_answer;
        }
      }
      myAnswer.topic_id = topics[k].id;
      console.log(myAnswer);
      _answer.answer.push(myAnswer);
    }
    _answer = [_answer];
    wx.showModal({
      title: '提示',
      content: '是否确认提交?',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '上传中',
          })
          wx.request({
            url: app.globalData.URL + '/kmapping/WebAppAjax/submitAnswerByPapers?' + app.globalData.URLBOOL,
            method: 'GET',
            data: {
              task_id: task_id,
              answer: JSON.stringify(_answer),
              user_id: user_id,
              kmapping_id: kmapping_id
            },
            success(res) {
              wx.hideLoading();
              if (res.data.error_code == 0) {
                wx.showToast({
                  title: '成功',
                  icon: 'success',
                  duration: 2000
                })
                _this.getaddTaskLog(3) //学习上报
                // wx.removeStorageSync(user_id + '-' + task_id + '-' + paper_ids);
                _this.getAnswerInfo();
              } else {
                wx.showToast({
                  title: res.data.error_msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          })
        } else if (res.cancel) {
          return;
        }
      }
    })
  },
  /**
   * 资源学习上报
   */
  getaddTaskLog: function(type) {
    var _this = this;
    wx.request({
      url: app.globalData.URL + '/kmapping/WebAppAjax/addTaskLog?' + app.globalData.URLBOOL,
      dataType: 'json',
      method: 'GET',
      data: {
        resource_id: _this.data.resource_id,
        type: type,
        task_id: _this.data.task_id,
        structure_id: _this.data.structure_id,
        kmapping_id: _this.data.kmapping_id
      },
      success: function(res) {
        var _res = res.data;
        if (_res.error_code == 0) {}
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    var type = options.target_type;
    var resourceId = options.target_id;
    var taskId = options.task_id;
    var kmappingId = options.kmapping_id;
    var structureId = options.structure_id;
    console.log(options);
    _this.setData({
      url: app.globalData.URL,
      resource_id: resourceId,
      type: type,
      task_id: taskId,
      structure_id: structureId,
      kmapping_id: kmappingId
    })
    _this.getRsourceDetailInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var _this = this,
      user_id = wx.getStorageSync('userId'),
      problemArray = _this.data.problemArray,
      download_task_id = _this.data.download_task_id,
      hxStatus = _this.data.hxStatus,
      task_id = _this.data.task_id,
      paper_ids = _this.data.paper_ids,
      onlineState = _this.data.onlineState;
    
    if (hxStatus) { //拍题返回答题卡
      _this.setData({
        testState: false
      })
      wx.showLoading({
        title: '加载中...',
        //mask: true
      })
      wx.request({
        url: app.globalData.URL + '/kmapping/WebAppAjax/getTopicStatusBySplitAndTask?' + app.globalData.URLBOOL,
        method: 'GET',
        data: {
          task_id: _this.data.task_id,
          kmapping_download_task_id: download_task_id,
          paper_ids: paper_ids
        },
        success: function(res) {
          var _res = res.data;
          if (_res.error_code == 0) {
            console.log(_res);
            var topicData = _res.data[0].topics;
            var split_status = 0;
            for (var i = 0; i < topicData.length; i++) {
              if (topicData[i].user_answer_paper_status == 1) {
                split_status = 1;
                problemArray[0].topics[i].user_answer_paper_status = 1;
              }
            }
            if (split_status == 1) {
              // wx.setStorageSync(user_id + '-' + task_id + '-' + paper_ids, problemArray);
              wx.hideLoading();
              _this.setData({
                problemArray: problemArray,
              })
            } else if (split_status == 0) {
              var _problemArray = wx.getStorageSync(user_id + '-' + task_id + '-' + paper_ids);
              console.log(_problemArray);
              _this.setData({
                problemArray: _problemArray,
                hxStatus: false
              })
              _this.fromCache();
            }
          } else {
            wx.hideLoading();
            wx.showToast({
              title: _res.error_msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
    if (onlineState) { //在线答题发回答题卡
      _this.getAnswerInfo();
      // var topics = problemArray[0].topics;
      // for (var i = 0; i < topics.length; i++) {
      //   if (topics[i].answer_flag == 1) {
      //     _this.setData({
      //       testState: false
      //     })
      //     break;
      //   }
      // }
      _this.setData({
        onlineState: false //将返回标识初始化
      })
      // wx.setStorageSync(user_id + '-' + task_id + '-' + paper_ids, problemArray);
      // _this.fromCache();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})